package com.jingran.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 * @author jingran
 */
@Component
public class SpringRedisUtils {

    @Autowired
    RedisTemplate redisTemplate;

    public boolean set(String key,String value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String key,String value,long time){
        try {
            if(time > 0){
                redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            }else {
                set(key, value);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public String get(String key){
        return key == null ? null : (String) redisTemplate.opsForValue().get(key);
    }

    public boolean expire(String key,long time){
        try {
            if(time > 0){
                redisTemplate.expire(key,time,TimeUnit.SECONDS);
            }else {
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean exists(String key){
        if(redisTemplate.hasKey(key)){
            return true;
        }else{
            return false;
        }
    }

    public void delete(String key){
        redisTemplate.delete(key);
        System.out.println("删除key成功");
    }
}
